package nc.bs.voucher.report.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.ufida.report.frquery.model.FrSimFilterValue;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.voucer.print.PrintSumUtils;
import nc.bs.voucher.report.VoucherReportResultViewMeta;
import nc.bs.voucher.report.VoucherReportVO;
import nc.bs.voucher.report.itf.VoucherReportService;
import nc.itf.gl.voucher.IVoucher;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.pub.smart.context.SmartContext;
import nc.pub.smart.data.DbTable;
import nc.pub.smart.metadata.MetaData;
import nc.vo.gl.pubvoucher.VoucherVO;
import nc.vo.me.report.pub.DataViewUtil;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.report.ReportTempTableUtil;

public class VoucherReportServiceImpl implements VoucherReportService {
	private BaseDAO baseDAO;
	private IVoucher vocherService;
	
	@SuppressWarnings("unchecked")
	@Override
	public DbTable process(SmartContext context, Map<String, Object> item) throws BusinessException {
		try {
			String sql = this.getVoucherSQL(context, item);
			Object obj = this.getBaseDAO().executeQuery(sql, new MapListProcessor());
			if(obj == null) return this.createReportTable();
			List<Map<String, Object>> lists = (List<Map<String, Object>>)obj;
			if(lists.isEmpty()) return this.createReportTable();
			List<VoucherReportVO> listvos = new ArrayList<VoucherReportVO>();
			listvos = this.ListMapToListVoucherReportVO(listvos, lists);
			if(listvos.isEmpty()) return this.createReportTable();
			ReportTempTableUtil tmptableutils = new ReportTempTableUtil();
			DbTable reportTable = this.createReportTable();
			if(listvos.size()>0){
				tmptableutils.insertIntoTempTable(reportTable,
						listvos.toArray(new VoucherReportVO[0]));
				return reportTable;
			}else{
				return this.createReportTable();
			}
			
		}catch(BusinessException e) {
			throw new BusinessException(e.getMessage());
		}
	}
	/**
	 * 转化List中的map
	 * @param listzcxmvos 最终返回的结果集
	 * @param lists 凭证查询汇总
	 * @return
	 * @throws BusinessException
	 */
	protected List<VoucherReportVO> ListMapToListVoucherReportVO(List<VoucherReportVO> listvos, List<Map<String, Object>> lists) throws BusinessException{
		for(Map<String, Object> map : lists) {
			VoucherReportVO reportVO = new VoucherReportVO();
			VoucherVO vo = this.getVocherService().queryByPk(map.get("pk_voucher").toString());
			if(vo == null) continue;
			int printCount = PrintSumUtils.getPrintCount(vo);
			UFDouble attachment = map.get("attachment") == null ? new UFDouble(0) : new UFDouble(map.get("attachment").toString());
			UFDouble hj = attachment.add(new UFDouble(printCount));
			reportVO.setAttributeValue("voucher_year", map.get("year"));
			reportVO.setAttributeValue("orgcode", map.get("orgcode"));
			reportVO.setAttributeValue("orgname", map.get("orgname"));
			reportVO.setAttributeValue("voucher_year", map.get("year"));
			reportVO.setAttributeValue("period", map.get("period"));
			reportVO.setAttributeValue("voucher_no", map.get("voucher_no"));
			reportVO.setAttributeValue("attachment", attachment.getDouble());
			reportVO.setAttributeValue("pzsum", printCount);
			reportVO.setAttributeValue("hj", hj);
			listvos.add(reportVO);
		}
		return  listvos;
	}
	
	/**
	 * 获取凭证打印数量
	 * @param pk_voucher
	 * @return
	 * @throws BusinessException
	 */
	public UFDouble getPrintSum(Object pk_voucher) throws BusinessException{
		if(pk_voucher == null ) {return new UFDouble(0);}
		VoucherVO voucherVO = this.getVocherService().queryByPk(pk_voucher.toString());
		
		return null;
	}
	
	/**
	 * 获取凭证查询SQL
	 * @param context
	 * @param item
	 * @return
	 * @throws BusinessException
	 */
	@SuppressWarnings("unchecked")
	protected String getVoucherSQL(SmartContext context, Map<String, Object> item) throws BusinessException{
		Object year = item.get("year");
		Object period = item.get("period");
		Object pk_org = item.get("pk_org");
		Object voucher_no = item.get("voucher_no");
		if(!item.isEmpty()&&  year != null || voucher_no != null 
				|| period != null || pk_org != null){
			year = item.get("year");
			voucher_no = item.get("voucher_no");
			period = item.get("period");
			pk_org = item.get("pk_org");
		}else{
			List<Object> lmaps = (List<Object>)context.getAttribute("key_lw_report_query_items");
			if(lmaps != null ){
				for(Object obj :  lmaps){
					FrSimFilterValue sim = (FrSimFilterValue)obj;
					String filterCode = sim.getFilterCode();
					switch (filterCode){
						case "pk_org":
							pk_org = sim.getValues();
							break;
						case "year":
							year = sim.getValues();
							break;
						case "voucher_no":
							voucher_no = sim.getValues();
							break;
						case "period":
							period = sim.getValues();
							break;
					}
				}
			}
		}
		return this.buildVoucherSQL(year, voucher_no, period,pk_org);
	}
	
	/**
	 * 构建凭证查询接口
	 * @param year       年度
	 * @param voucher_no 凭证号
	 * @param period     期间
	 * @return
	 * @throws BusinessException
	 */
	@SuppressWarnings({ "unchecked", "restriction" })
	protected String buildVoucherSQL(Object year, Object voucher_no,Object period,Object pk_org) throws BusinessException{
		StringBuilder sql = new StringBuilder();
		sql.append(" select  ");
		sql.append("   gv.pk_voucher, gv.year, gv.num voucher_no, gv.attachment, ");
		sql.append("   gv.adjustperiod period,gv.pk_org, oos.code orgcode, oos.name orgname  ");
		sql.append(" from gl_voucher gv  ");
		sql.append(" left join org_orgs oos on  gv.pk_org = oos.pk_org  ");
		sql.append("  where gv.dr = 0 and 1 = 1 ");
		if(pk_org != null ){
			if(pk_org instanceof List){
				List<String> orgs = (List<String>)pk_org;
				String[] arrorgs = orgs.toArray(new String[orgs.size()]);
				 sql.append(" and gv.pk_org in ('"+StringUtils.join(arrorgs, "'")+"') ");
			}else{
				sql.append("  and gv.pk_org = '"+pk_org+"'  ");
			}
		}
		if(year != null ){
			if(year instanceof List){
				List<String> years = (List<String>)year;
				String[] arryears = years.toArray(new String[years.size()]);
				 sql.append(" and gv.year in ('"+StringUtils.join(arryears, "'")+"') ");
			}else{
				sql.append("  and gv.year = '"+year+"'   ");
			}
		}
		if(voucher_no != null ){
			if(voucher_no instanceof List){
				List<String> voucher_nos = (List<String>)voucher_no;
				String[] arrvoucher_nos = voucher_nos.toArray(new String[voucher_nos.size()]);
				 sql.append(" and gv.num  in ('"+StringUtils.join(arrvoucher_nos, "'")+"') ");
			}else{
				sql.append("  and num  = '"+voucher_no+"'   ");
			}
		}
		if(period != null ){
			if(period instanceof List){
				List<String> periods = (List<String>)period;
				String[] arrperiods = periods.toArray(new String[periods.size()]);
				 sql.append(" and gv.adjustperiod  in ('"+StringUtils.join(arrperiods, "'")+"') ");
			}else{
				sql.append("  and gv.adjustperiod  = '"+period+"'   ");
			}
		}
		sql.append("  order by gv.year asc ");
		return sql.toString();
	}

	public BaseDAO getBaseDAO() {
		return baseDAO == null ? new BaseDAO() : baseDAO;
	}
	
	
	@SuppressWarnings("static-access")
	private DbTable createReportTable() {
		MetaData reportMeta = new DataViewUtil()
		.getMetaData(new VoucherReportResultViewMeta());
		ReportTempTableUtil tool = new ReportTempTableUtil();
	return tool.createTempTable(reportMeta);
	}

	public IVoucher getVocherService() {
		if(vocherService == null ) {
			vocherService =  NCLocator.getInstance().lookup(IVoucher.class);
		}
		return vocherService;
	}
	
}

